using System.Collections.Generic;
using System.Linq;

namespace LuceneSearch.ContactApp.Indexing
{
    public class EntityIndexer
    {
        private readonly IEntityIndexProcessor[] processors;

        public EntityIndexer(IEntityIndexProcessor[] processors)
        {
            this.processors = processors;
        }

        public void Process(IEnumerable<IndexWorkItem> items)
        {
            foreach (var typeGroup in items.GroupBy(x => x.IndexWorkType))
            {
                ProcessGroup(typeGroup);                
            }
        }

        private void ProcessGroup(IGrouping<IndexWorkType, IndexWorkItem> typeGroup)
        {
            foreach (var processor in processors)
            {
                if (processor.CanProcess(typeGroup.Key))
                    processor.Process(typeGroup.Select(x => x.Entity));
            }
        }
    }
}